# import sys
# import threading
# from pympler import tracker,summary,muppy
# #memory_tracker=tracker.SummaryTracker()
import gc
import os
# import shutil
# from PyQt5.QtCore import pyqtSignal
from PyQt5.QtChart import QChart, QLineSeries, QValueAxis, QChartView
# from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QMessageBox
# from PyQt5.QtGui import *
from numba import jit
from TDC20200916 import *
from cursorsetting import *
from Expsetting import *
from PyQt5.Qt import *
# from pyqtgraph import PlotWidget
# from PyQt5 import QtCore
import numpy as np
import pyqtgraph as pq
import datetime
# import matplotlib
# import matplotlib.pyplot as plt
# import time
# from collections import Counter

try:
    import QuTAG
except:
    print("Time Tagger wrapper QuTAG.py is not in the search path.")
qutag = QuTAG.QuTAG()



@jit
def cal(data1, data2, hist1, hist2, hist3, cursor_1_1, cursor_1_2, cursor_2_1, cursor_2_2, cursor_3_1, cursor_3_2):

    data4 = hist1
    data5 = hist2
    data6 = hist3
    sweeps = 0
    det1 = 0
    det2 = 0
    det3 = 0
    count1 = 0
    count2 = 0
    count3 = 0
    coin12 = 0
    coin13 = 0
    coin23 = 0
    coin123 = 0
    aa = np.arange(0,len(data1),1)
    for i in aa:#np.arange(0, len(data1), 1):
        if data2[i] == 4:
            sweeps = sweeps + 1
            #if det1 != 0 and det2 != 0:
            if det1 == 1 and det2 == 1:
                coin12 = coin12 + 1
                if det3 != 0:
                    coin13 = coin13 + 1
                    coin23 = coin23 + 1
                    coin123 = coin123 + 1
                else:
                    pass
            elif det1 != 0 and det3 != 0:
                coin13 = coin13 + 1
            elif det2 != 0 and det3 != 0:
                coin23 = coin23 + 1
            else:
                pass
            det1 = 0
            det2 = 0
            det3 = 0
        elif data2[i] == 1 and -1 < data1[i] < 200000:
            x = int(data1[i])
            data4[x][1] = data4[x][1] + 1
            if cursor_1_1 < data1[i] < cursor_1_2:  # jiacursor

                #  channeltime1[i] = data1[i]
                det1 = det1 + 1
                count1 = count1 + 1
        elif data2[i] == 2 and 0 < data1[i] < 200000:
            x = int(data1[i])
            #data5[x][1] = data5[x][1] + 1
            # hist_ch2[data1[i]][1] = hist_ch2[data1[i]][1]+1
            if cursor_2_1 < data1[i] < cursor_2_2:
                data5[x][1] = data5[x][1] + 1
                # channeltime2[i] = data1[i]
                det2 = det2 + 1
                count2 = count2 + 1
        elif data2[i] == 3 and -1 < data1[i] < 200000:
            x = int(data1[i])
            data6[x][1] = data6[x][1] + 1
            # hist_ch3[data1[i]][1] = hist_ch3[data1[i]][1]+1
            if cursor_3_1 < data1[i] < cursor_3_2:
                # channeltime3[i] = data1[i]
                det3 = det3 + 1
                count3 = count3 + 1
        else:
            pass

    return sweeps, count1, count2, count3, coin12, coin13, coin23, coin123, data4, data5, data6  # , hist_ch1


class SetExpTime(QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(SetExpTime, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Set ExpTime")
        self.Button_SetExpTime_ok.clicked.connect(self.ExpTime)
        self.Set_Exp_Time.setText('20')
        self.Set_Exp_ExposureTime.setText('1')

    def ExpTime(self):
        self.ExpTime_set = self.Set_Exp_Time.text()
        self.ExposureTime_set = self.Set_Exp_ExposureTime.text()
        self.Set_Exp_Time.setText(self.ExpTime_set)
        self.close()
        return self.ExpTime_set, self.ExposureTime_set


class SetCursor(QDialog, Ui_CursorSetting):
    def __init__(self, parent=None):
        super(SetCursor, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Set Cursor")
        self.Set_Cursorsetting_ok.clicked.connect(self.setcursor)

    def setcursor(self):
        cursor_1_1 = self.Set_Cursor1_Channel1.text()
        cursor_1_2 = self.Set_Cursor2_Channel1.text()
        cursor_2_1 = self.Set_Cursor1_Channel2.text()
        cursor_2_2 = self.Set_Cursor2_Channel2.text()
        cursor_3_1 = self.Set_Cursor1_Channel3.text()
        cursor_3_2 = self.Set_Cursor2_Channel3.text()
        self.close()
        return cursor_1_1, cursor_1_2, cursor_2_1, cursor_2_2, cursor_3_1, cursor_3_2


class Window(QMainWindow, Ui_MainWindow):
    #signal1 = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.stop_trigger = 0
        self.Time_Waiting_GetTimestamps = 1

        # 测量时间初始值
        self.ExpTimeSetting = 10000
        self.ExposureTimeSetting = 1000  # ms

        # 光标设置
        self.input_chart_range_1_1 = 0
        self.input_chart_range_1_2 = 200000
        self.input_chart_range_2_1 = 0
        self.input_chart_range_2_2 = 200000
        self.input_chart_range_3_1 = 0
        self.input_chart_range_3_2 = 200000
        self.chart_range_1_1.setText('19147')
        self.chart_range_1_2.setText('19217')
        self.chart_range_2_1.setText('25974')
        self.chart_range_2_2.setText('26044')
        self.chart_range_3_1.setText('52284')
        self.chart_range_3_2.setText('52421')
        self.channel1_cursor1 = 15435
        self.channel1_cursor2 = 15489
        self.channel2_cursor1 = 51069
        self.channel2_cursor2 = 51128
        self.channel3_cursor1 = 50000
        self.channel3_cursor2 = 50070
        self.cursor_1_1.setText('19147')
        self.cursor_1_2.setText('19217')
        self.cursor_2_1.setText('25974')
        self.cursor_2_2.setText('26044')
        self.cursor_3_1.setText('50000')
        self.cursor_3_2.setText('50070')
        self.filewritestop = None
        self.path = os.getcwd()

        self.Time_Start = datetime.datetime.now()
        self.Button_Start.clicked.connect(self.starting)
        self.Button_Stop.clicked.connect(self.stopping)
        self.action_Exptime.triggered.connect(self.SetExpTime)
        # self.Action_Cursor.triggered.connect(self.SetCursor)
        self.ViewChart_Range_set.clicked.connect(self.SetChartrange)
        self.Cursor_Set.clicked.connect(self.SetCursor)

    def SetExpTime(self):
        self.SetExpTimeWindow = SetExpTime()
        self.SetExpTimeWindow.exec_()
        self.exptime = self.SetExpTimeWindow.ExpTime()
        self.ExpTimeSetting = int(self.exptime[0])
        self.ExposureTimeSetting = int(float(self.exptime[1]) * 1000)

    def SetCursor(self):
        # self.SetCursorWindow = SetCursor()
        # self.SetCursorWindow.exec_()
        # cursor_result = self.SetCursorWindow.setcursor()##zichuangkou
        # self.channel1_cursor1 = float(cursor_result[0])
        # self.channel1_cursor2 = float(cursor_result[1])
        # self.channel2_cursor1 = float(cursor_result[2])
        # self.channel2_cursor2 = float(cursor_result[3])
        # self.channel3_cursor1 = float(cursor_result[4])
        # self.channel3_cursor2 = float(cursor_result[5])
        # print(self.channel1_cursor1)
        self.channel1_cursor1 = float(self.cursor_1_1.text())
        self.channel1_cursor2 = float(self.cursor_1_2.text())
        self.channel2_cursor1 = float(self.cursor_2_1.text())
        self.channel2_cursor2 = float(self.cursor_2_2.text())
        self.channel3_cursor1 = float(self.cursor_3_1.text())
        self.channel3_cursor2 = float(self.cursor_3_2.text())

    def SetChartrange(self):
        self.input_chart_range_1_1 = float(self.chart_range_1_1.text())
        self.input_chart_range_1_2 = float(self.chart_range_1_2.text())
        self.input_chart_range_2_1 = float(self.chart_range_2_1.text())
        self.input_chart_range_2_2 = float(self.chart_range_2_2.text())
        self.input_chart_range_3_1 = float(self.chart_range_3_1.text())
        self.input_chart_range_3_2 = float(self.chart_range_3_2.text())

    def stopping(self):
        self.stop_trigger = 1

    def starting(self):
        #self.chart_ch = QChart()
        self.filewritestop = 0
        self.count_sweeps = 0
        self.count_channel1 = 0
        self.count_channel2 = 0
        self.count_channel3 = 0
        self.count_coin12 = 0
        self.count_coin13 = 0
        self.count_coin23 = 0
        self.count_coin123 = 0
        self.count_pro1 = 0
        self.count_pro2 = 0
        self.count_pro3 = 0
        self.count_pro12 = 0
        self.count_pro13 = 0
        self.count_pro23 = 0
        self.count_pro123 = 0
        self.g12 = 0
        self.g13 = 0
        self.g23 = 0
        self.alpha_1_23 = 0
        self.g12_err = 0
        self.g13_err = 0
        self.g23_err = 0
        self.alpha_1_23_err = 0
        self.histname_ch1 = None
        self.histname_ch2 = None
        self.histname_ch3 = None

        self.saveindex = self.save_index.text()

        self.file_originnaldata = self.path + '\DataRecording' + '\originaldata.txt'
        self.histname_ch1 = self.path + '\DataRecording' + '\hist_ch1.CSV'
        if os.path.exists(self.histname_ch1):  # 如果文件存在
            os.remove(self.histname_ch1)
        else:
            pass  # 则返回文件不存在
        self.histname_ch2 = self.path + '\DataRecording' + '\hist_ch2.CSV'
        if os.path.exists(self.histname_ch2):  # 如果文件存在
            os.remove(self.histname_ch2)
        else:
            pass  # 则返回文件不存在
        self.histname_ch3 = self.path + '\DataRecording' + '\hist_ch3.CSV'
        if os.path.exists(self.histname_ch3):  # 如果文件存在
            os.remove(self.histname_ch3)
        else:
            pass  # 则返回文件不存在
        self.filename_result = self.path + '\DataRecording' + '\DataRecording.txt'
        if os.path.exists(self.filename_result):  # 如果文件存在
            os.remove(self.filename_result)
        else:
            pass  # 则返回文件不存在
        self.filename_result_sum = self.path + '\DataRecording' + '\DataRecording_sum.txt'
        #if os.path.exists(self.filename_result_sum):  # 如果文件存在
            #os.remove(self.filename_result_sum)
        #else:
            #pass  # 则返回文件不存在
        open(self.file_originnaldata, 'w')
        qutag.writeTimestamps(self.file_originnaldata, qutag.FILEFORMAT_ASCII)

        # initinal
        self.stop_trigger = 0
        self.count_sweeps = 0
        self.det2 = 0
        self.det3 = 0
        self.Result_Counts_2 = 0
        self.Result_Counts_3 = 0
        self.Result_Counts_Coin23 = 0
        # 0830
        self.hist_ch1 = np.zeros(shape=(200000, 2))
        self.hist_ch2 = np.zeros(shape=(200000, 2))
        self.hist_ch3 = np.zeros(shape=(200000, 2))
        for i in range(200000):
            self.hist_ch1[i][0] = i
            self.hist_ch2[i][0] = i
            self.hist_ch3[i][0] = i
        self.hist_ch1_0 = self.hist_ch1.T[0]
        self.hist_ch1_1 = self.hist_ch1.T[1]
        self.Time_Exp_Start = datetime.datetime.now()

        self.Result_Timestamps = qutag.getLastTimestamps(True)
        print('starttime', datetime.datetime.now())
        if self.stop_trigger == 0:
            self.timer = pq.QtCore.QTimer()
            self.timer.timeout.connect(self.update_data)
            self.timer.start(self.ExposureTimeSetting)  # shezhiTDCduqujiange
        else:
            pass
        # for i in range(self.ExpTimeSetting):
        #     time.sleep(2)
        #     self.signal1.connect(self.update_data)
        #     self.signal1.emit()

    def update_data(self):
        Time_Exp_Stop = datetime.datetime.now()
        Exp_Time = (Time_Exp_Stop - self.Time_Exp_Start).total_seconds()
        if self.stop_trigger == 0 and Exp_Time < self.ExpTimeSetting:
            self.Result_Timestamps = qutag.getLastTimestamps(True)
            self.Result_Timestamps2 = []
            self.Result_Timestamps3 = []
            data = np.array(self.Result_Timestamps)

            data00 = np.trunc(data[0] / 10)  # / 10)  # * 100
            data11 = data[1]
            self.result = cal(data00, data11, self.hist_ch1, self.hist_ch2, self.hist_ch3, self.channel1_cursor1,
                              self.channel1_cursor2, self.channel2_cursor1,
                              self.channel2_cursor2, self.channel3_cursor1, self.channel3_cursor2)
            # print(self.path)

            self.hist_ch1 = self.result[-3]
            self.hist_ch2 = self.result[-2]
            self.hist_ch3 = self.result[-1]
            # self.hist_ch1=result[-1]
            # print(len(result[-1]))
            self.count_sweeps = self.count_sweeps + self.result[0]
            self.count_channel1 = self.count_channel1 + self.result[1]
            self.count_channel2 = self.count_channel2 + self.result[2]
            self.count_channel3 = self.count_channel3 + self.result[3]
            self.count_coin12 = self.count_coin12 + self.result[4]
            self.count_coin13 = self.count_coin13 + self.result[5]
            self.count_coin23 = self.count_coin23 + self.result[6]
            self.count_coin123 = self.count_coin123 + self.result[7]
            if self.count_sweeps != 0:
                self.count_pro1 = round(self.count_channel1 / self.count_sweeps,5)
                self.count_pro2 = round(self.count_channel2 / self.count_sweeps,5)
                self.count_pro3 = round(self.count_channel3 / self.count_sweeps,5)
                self.count_pro12 = round(self.count_coin12 / self.count_sweeps,5)
                self.count_pro13 = round(self.count_coin13 / self.count_sweeps,5)
                self.count_pro23 = round(self.count_coin23 / self.count_sweeps,5)
                self.count_pro123 = round(self.count_coin123 / self.count_sweeps,5)
            else:
                pass

            # 数据展示
            self.Result_Sweeps.setText(str(self.count_sweeps))
            self.Result_Counts_Channel_1.setText(str(self.count_channel1))
            self.Result_Counts_Channel_2.setText(str(self.count_channel2))
            self.Result_Counts_Channel_3.setText(str(self.count_channel3))
            self.Result_Counts_Coin_12.setText(str(self.count_coin12))
            self.Result_Counts_Coin_13.setText(str(self.count_coin13))
            self.Result_Counts_Coin_23.setText(str(self.count_coin23))
            self.Result_Counts_Coin_123.setText(str(self.count_coin123))
            self.Result_Counts_pro_Channel_1.setText(str(self.count_pro1))
            self.Result_Counts_pro_Channel_2.setText(str(self.count_pro2))
            self.Result_Counts_pro_Channel_3.setText(str(self.count_pro3))
            self.Result_Counts_pro_Coin12.setText(str(self.count_pro12))
            self.Result_Counts_pro_Coin13.setText(str(self.count_pro13))
            self.Result_Counts_pro_Coin1_23.setText(str(self.count_pro23))
            self.Result_Counts_pro_Coin123.setText(str(self.count_pro123))

            if self.result[1] != 0 and self.result[2] != 0:
                # self.g12 = round(result[4] * result[0] / (result[1] * result[2]), 3)
                self.g12 = round(self.count_coin12 * self.count_sweeps / (self.count_channel1 * self.count_channel2), 5)
                self.g12_err = round(np.sqrt(
                    (self.count_coin12 / (self.count_channel1 ** 2 * self.count_channel2)) ** 2 * self.count_channel1 +
                    (self.count_coin12 / (self.count_channel2 ** 2 * self.count_channel1)) ** 2 * self.count_channel2 +
                    (1 / (self.count_channel1 * self.count_channel2)) ** 2 * self.count_coin12) * self.count_sweeps,5)
            if self.result[1] != 0 and self.result[3] != 0:
                # self.g13 = round(result[5] * result[0] / (result[1] * result[3]), 3)
                self.g13 = round(self.count_coin13 * self.count_sweeps / (self.count_channel1 * self.count_channel3), 5)
                self.g13_err = round( np.sqrt(
                    (self.count_coin13 / (self.count_channel1 ** 2 * self.count_channel3)) ** 2 * self.count_channel1 +
                    (self.count_coin13 / (self.count_channel3 ** 2 * self.count_channel1)) ** 2 * self.count_channel3 +
                    (1 / (self.count_channel1 * self.count_channel3)) ** 2 * self.count_coin13) * self.count_sweeps,5)
                # if result[2] != 0 and result[3] != 0:
                # self.g23 = round(result[6] * result[0] / (result[2] * result[3]), 3)
                self.g23 = round((self.count_coin12 + self.count_coin13) * self.count_sweeps / (
                        (self.count_channel2 + self.count_channel3) * self.count_channel1), 5)  # 23通道同共同计数，再和1通道关联
                self.g23_err = round(np.sqrt(
                    ((self.count_coin12 + self.count_coin13) / (self.count_channel1 ** 2 * (
                            self.count_channel2 + self.count_channel3))) ** 2 * self.count_channel1 +
                    ((self.count_coin12 + self.count_coin13) / (
                            (self.count_channel2 + self.count_channel3) ** 2 * self.count_channel1)) ** 2 * (
                            self.count_channel2 + self.count_channel3) +
                    (1 / (self.count_channel1 * (self.count_channel2 + self.count_channel3))) ** 2 * (
                            self.count_coin12 + self.count_coin13)) * self.count_sweeps, 5)

            if self.result[4] != 0 and self.result[5] != 0:
                # self.alpha_1_23 = round(result[7] * result[1] / (result[4] * result[5]), 3)
                self.alpha_1_23 = round(
                    self.count_coin123 * self.count_channel1 / (self.count_coin12 * self.count_coin13), 5)
                self.alpha_1_23_err = round(np.sqrt(
                    (self.count_coin123 / (self.count_coin12 * self.count_coin13)) ** 2 * self.count_channel1 +
                    (self.count_channel1 / (self.count_coin12 * self.count_coin13)) ** 2 * self.count_coin123
                    + (self.count_channel1 * self.count_coin123 / (
                                self.count_coin12 ** 2 * self.count_coin13)) ** 2 * self.count_coin12 +
                    (self.count_channel1 * self.count_coin123 / (
                                self.count_coin13 ** 2 * self.count_coin12)) ** 2 * self.count_coin13),5)

            self.Result_Counts_g2_12.setText(str(self.g12))
            self.Result_Counts_g2_13.setText(str(self.g13))
            self.Result_Counts_g2_23.setText(str(self.g23))
            self.Result_Counts_alpha1_23.setText(str(self.alpha_1_23))
            self.Result_Counts__err_g2_12.setText(str(self.g12_err))
            self.Result_Counts__err_g2_13.setText(str(self.g13_err))
            self.Result_Counts__err_g2_1_23.setText(str(self.g23_err))
            self.Result_Counts_err_alpha1_23.setText(str(self.alpha_1_23_err))

            with open(self.filename_result, 'a') as ResultRecording:
                ResultRecording.write(
                    str(self.result[0]) + ' ' + str(self.result[1]) + ' ' + str(self.result[2]) + ' ' + str(
                        self.result[3]) + ' ' +
                    str(self.result[4]) + ' ' + str(self.result[5]) + ' ' + str(self.result[6]) + ' ' + str(
                        self.result[7]) + '  ' + str(datetime.datetime.now()) + '\n')
                ResultRecording.close()
            # channel1 data



            # channel1 data
            # if 'self.chart_ch1' in vars() and 'self.series_ch1' in vars():
            #     self.chart_ch1.removeSeries(self.series_ch1)
            #     del self.chart_ch1, self.series_ch1
            #     gc.collect()
            # else:
            #     pass

            self.chart_ch1 = QChart()
            self.chart_ch1.legend().setVisible(False)
            self.Counting_Channel_1.setChart(self.chart_ch1)
            self.series_ch1 = QLineSeries()

            #self.series_ch1.setUseOpenGL(True)
            # self._chart.removeSeries(self.series)
            # self.series.clear()

            # self.series.setName('曲线')
            for i in range(200000):
                self.series_ch1.append(self.hist_ch1[i][0], self.hist_ch1[i][1])
            self.chart_ch1.addSeries(self.series_ch1)
            self.chart_ch1_0=self.chart_ch1

            self.Counting_Channel_1.setChart(self.chart_ch1)
            self.Counting_Channel_1.setRubberBand(QChartView.HorizontalRubberBand)
            self.axisx = QValueAxis()
            self.axisx.setRange(self.input_chart_range_1_1, self.input_chart_range_1_2)
            self.axisy = QValueAxis()
            # self.axisy.setRange(0, 100)
            self.chart_ch1.setAxisX(self.axisx, self.series_ch1)
            self.chart_ch1.setAxisY(self.axisy, self.series_ch1)

            #
            # channel2 data
            self.chart_ch2 = QChart()
            self.chart_ch2.legend().setVisible(False)
            self.Counting_Channel_2.setChart(self.chart_ch2)
            self.series_ch2 = QLineSeries()
            # self.series_ch2.setUseOpenGL(True)
            for i in range(200000):
                self.series_ch2.append(self.hist_ch2[i][0], self.hist_ch2[i][1])
            self.chart_ch2.addSeries(self.series_ch2)
            self.chart_ch2_0 = self.chart_ch2
            self.Counting_Channel_2.setChart(self.chart_ch2)
            self.Counting_Channel_2.setRubberBand(QChartView.HorizontalRubberBand)
            self.axisx2 = QValueAxis()
            self.axisx2.setRange(self.input_chart_range_2_1, self.input_chart_range_2_2)
            self.axisy2 = QValueAxis()
            # self.axisy2.setRange(-0, 100)
            self.chart_ch2.setAxisX(self.axisx2, self.series_ch2)
            self.chart_ch2.setAxisY(self.axisy2, self.series_ch2)

            # channel3 data
            self.chart_ch3 = QChart()
            self.chart_ch3.legend().setVisible(False)
            self.Counting_Channel_3.setChart(self.chart_ch3)
            self.series_ch3 = QLineSeries()
            # self.series_ch3.setUseOpenGL(True)
            for i in range(200000):
                self.series_ch3.append(self.hist_ch3[i][0], self.hist_ch3[i][1])
            self.chart_ch3.addSeries(self.series_ch3)
            self.chart_ch3_0 = self.chart_ch3
            self.Counting_Channel_3.setChart(self.chart_ch3)
            self.Counting_Channel_3.setRubberBand(QChartView.HorizontalRubberBand)
            self.axisx3 = QValueAxis()
            self.axisx3.setRange(self.input_chart_range_3_1, self.input_chart_range_3_2)
            self.axisy3 = QValueAxis()
            # self.axisy3.setRange(0, 100)
            self.chart_ch3.setAxisX(self.axisx3, self.series_ch3)
            self.chart_ch3.setAxisY(self.axisy3, self.series_ch3)
            #memory_tracker.print_diff()

        else:
            self.Counting_Channel_1.setChart(self.chart_ch1_0)
            self.Counting_Channel_2.setChart(self.chart_ch2_0)
            self.Counting_Channel_3.setChart(self.chart_ch3_0)
            # self.Counting_Channel_1.setRubberBand(QChartView.HorizontalRubberBand)
            # self.chart_ch1.setAxisX(self.axisx, self.series_ch1)
            # self.chart_ch1.setAxisY(self.axisy, self.series_ch1)
            self.timer.stop()
            self.stop_trigger = 1
            if self.filewritestop == 0:
                with open(self.filename_result_sum, 'a') as ResultRecording1:
                    ResultRecording1.write(self.saveindex + '\t' +
                        str(self.count_sweeps) + '\t' + str(self.count_channel1) + '\t' + str(
                            self.count_channel2) + '\t' + str(self.count_channel3) + '\t' + str(
                            self.count_coin12) + '\t' + str(self.count_coin13) + '\t' + str(
                            self.count_coin23) + '\t' + str(
                            self.count_coin123) + '\t' + str(self.count_pro1) + '\t' +
                        str(self.count_pro2) + '\t' + str(self.count_pro3) + '\t' + str(self.count_pro12) + '\t' + str(
                            self.count_pro13) + '\t' + str(self.count_pro23) + '\t' + str(self.count_pro123) + '\t' + str(
                            self.g12) + '\t' + str(self.g13) + '\t' + str(self.g23) + '\t' + str(
                            self.alpha_1_23) + '\t' + str(
                            self.g12_err) + '\t' + str(self.g13_err) + '\t' + str(self.g23_err) + '\t' +
                        str(self.alpha_1_23_err) + '\t' + str(datetime.datetime.now()) + '\n')
                    ResultRecording1.close()

                self.histname_ch1 = self.path + '\DataRecording' + '\hist_ch1.CSV'
                with open(self.histname_ch1, 'w') as f_handle1:
                    np.savetxt(f_handle1, [x for x in self.hist_ch1], delimiter=',')
                    f_handle1.close()
                self.histname_ch2 = self.path + '\DataRecording' + '\hist_ch2.CSV'
                with open(self.histname_ch2, 'w') as f_handle2:
                    np.savetxt(f_handle2, [x for x in self.hist_ch2], delimiter=',')
                    f_handle2.close()
                self.histname_ch3 = self.path + '\DataRecording' + '\hist_ch3.CSV'
                with open(self.histname_ch3, 'w') as f_handle3:
                    np.savetxt(f_handle3, [x for x in self.hist_ch3], delimiter=',')
                    f_handle3.close()
                del self.chart_ch1,self.chart_ch2,self.chart_ch3,self.series_ch1,self.series_ch2,self.series_ch3,f_handle1,f_handle2,f_handle3,ResultRecording1,self.hist_ch1_0,self.hist_ch1_1,self.Result_Timestamps,self.count_sweeps, self.count_channel1, self.count_channel2, self.count_channel3,self.count_coin12,self.count_coin13,self.count_coin23,self.count_coin123, self.count_pro1, self.count_pro2,self.count_pro3, self.count_pro12,self.count_pro13,self.count_pro23,self.count_pro123,self.g12,self.g13,self.g23,self.alpha_1_23,self.g12_err,self.g13_err,self.g23_err,self.alpha_1_23_err,self.histname_ch1,self.histname_ch2,self.histname_ch3,self.timer,self.stop_trigger,self.det2,self.det3,self.Result_Counts_2,self.Result_Counts_3,self.Result_Counts_Coin23,self.hist_ch1,self.hist_ch2,self.hist_ch3
                gc.collect()
                self.filewritestop = 1
                print('stoptime', datetime.datetime.now())
            else:
                pass
            qutag.writeTimestamps('', qutag.FILEFORMAT_NONE)
            sys.stdout.flush()
        # QMessageBox.about(self,"标题","运行结束")


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    window = Window()
    window.show()
    sys.exit(app.exec())
